package com.sfac.day03.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@WebListener
public class LogFileDestroyListener implements ServletContextListener {
    private final static Logger LOGGER = LoggerFactory.getLogger(LogFileDestroyListener.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        LOGGER.debug("====Init context ====");
        File file = new File("/log");
        if (file==null||!file.exists()) {
            return;
        }
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String currentDate = dtf.format(LocalDateTime.now());

        File[] files = file.listFiles();
        for (File file1 : files) {
            String file1Name = file1.getName();
            if (!file1Name.contains(currentDate)){
                file1.delete();
            }

        }

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        LOGGER.debug("==== Destory context====");

    }
}

